//
//  YSChatMessageCell.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/20.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSChatMessageCell.h"
#import "YYLabel.h"
#import "YSMessageDataBase.h"
#import "UIImage+YSAdd.h"

@interface YSChatMessageCell()

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) YYLabel *messageContentLabel;
@property (nonatomic, strong) UIButton *airView;

@end

@implementation YSChatMessageCell

- (void)setMessageFrame:(YSChatMessageFrame *)messageFrame {
    _messageFrame = messageFrame;

    self.headImageView.frame = messageFrame.headViewFrame;
    self.nameLabel.frame = messageFrame.nameLabelFrame;
    self.nameLabel.textAlignment = messageFrame.chatMessage.userType == YSUserTypeMe ? NSTextAlignmentRight : NSTextAlignmentLeft;
    self.messageContentLabel.frame = messageFrame.messageLabelFrame;
    self.airView.frame = messageFrame.airViewFrame;
    
    self.nameLabel.text = messageFrame.chatMessage.userName;
    self.headImageView.image = [UIImage imageNamed:messageFrame.chatMessage.userHeadImage];
    
    NSString *norImageName  = messageFrame.chatMessage.userType == YSUserTypeMe ? @"chat_send_nor" : @"chat_receive_nor";
    NSString *seleImageName = messageFrame.chatMessage.userType == YSUserTypeMe ? @"chat_send_p" : @"chat_receive_p";
    
    UIImage *norImage  = [UIImage resizebleImageWithName:norImageName];
    UIImage *seleImage = [UIImage resizebleImageWithName:seleImageName];
    [self.airView setBackgroundImage:norImage forState:UIControlStateNormal];
    [self.airView setBackgroundImage:seleImage forState:UIControlStateHighlighted];
    self.messageContentLabel.attributedText = messageFrame.attMessage;
}

#pragma mark - life cycle
+ (instancetype)cellWithTableView:(UITableView *)tableview {
    NSString *ID = @"ChatMessageCell";
    YSChatMessageCell *cell = [tableview dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[YSChatMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.tableView = tableview;
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupUI];
    }
    return self;
}

#pragma mark - setupUI
- (void)setupUI {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = [UIColor clearColor];
    
    [self addSubview:self.headImageView];
    [self addSubview:self.nameLabel];
    [self addSubview:self.airView];
    [self addSubview:self.messageContentLabel];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showMenuController:)];
    [self.airView addGestureRecognizer:longPress];
}

#pragma mark - event response
- (void)showMenuController:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyTextEvent)];
        UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteEvent)];
        
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setMenuItems:@[copyItem, deleteItem]];
        
        CGRect rect = [self.airView convertRect:self.airView.bounds toView:self.tableView.superview];
        CGFloat menuY = 0;
        if (rect.origin.y < 64) {
            menuY = CGRectGetMaxX(self.airView.frame) - 6;
            menuController.arrowDirection = UIMenuControllerArrowUp;
        } else {
            menuY = self.airView.frame.origin.y + 6;
        }
        
        CGRect menuLocation = CGRectMake(self.airView.center.x, menuY, 0, 0);
        [menuController setTargetRect:menuLocation inView:self];
        [menuController setMenuVisible:YES animated:YES];
    }
}

- (void)copyTextEvent {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.messageFrame.chatMessage.messageContent;
}

- (void)deleteEvent {
    if (self.deleteMessage) {
        self.deleteMessage(self.messageFrame);
    }
    
    NSString *deletestr = [NSString stringWithFormat:@"userId = '%zd'", self.messageFrame.chatMessage.userId];
    [YSMessageDataBase deleteData:deletestr];
}

/// 这个方法会在每一个menuItem生成的时候调用一次, 因此在方法体里就要根据action来判断是否需要显示在菜单里,
/// 如果不需要, 则返回NO. 也就是说, 如果你什么都不做, 直接返一个YES, 那么所有的默认菜单项都会显示出来
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copyTextEvent) || action == @selector(deleteEvent)) {
        return YES;
    }
    return NO;
}

/// 使用UIMenuController, 需要成为第一响应者
- (BOOL)canBecomeFirstResponder {
    return YES;
}

#pragma mark - 懒加载
- (UIImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc] init];
        _headImageView.layer.cornerRadius = 20;
        _headImageView.layer.masksToBounds = YES;
        _headImageView.userInteractionEnabled = YES;
    }
    return _headImageView;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.font = [UIFont systemFontOfSize:15.0f];
        _nameLabel.textColor = YSEmoticonRGB(136, 136, 136);
        _nameLabel.adjustsFontSizeToFitWidth = YES;
    }
    return _nameLabel;
}

- (YYLabel *)messageContentLabel {
    if (!_messageContentLabel) {
        _messageContentLabel = [[YYLabel alloc]init];
        _messageContentLabel.numberOfLines = 0;
        _messageContentLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
        _messageContentLabel.userInteractionEnabled = NO;
    }
    return _messageContentLabel;
}

- (UIButton *)airView {
    if (!_airView) {
        _airView = [UIButton buttonWithType:UIButtonTypeCustom];
        // shadowColor阴影颜色
        _airView.layer.shadowColor = [UIColor blackColor].CGColor;
        // shadowOffset阴影偏移,+x向右偏移，+y向下偏移，默认(0, -3),跟shadowRadius配合使用
        _airView.layer.shadowOffset = CGSizeMake(0, 0);
        // 阴影透明度，默认0
        _airView.layer.shadowOpacity = 0.1;
        // 阴影半径，默认3
        _airView.layer.shadowRadius = 4;
    }
    return _airView;
}

@end
